<template>
  <div class="container mx-auto px-4 py-8">
    <h1 class="text-2xl font-bold mb-6">统计报表</h1>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
      <div class="bg-white p-6 rounded-lg shadow-md">
        <h3 class="text-lg font-medium mb-4">各部门各种职称的教职工数量</h3>
        <div class="overflow-x-auto">
          <table class="min-w-full">
            <thead>
              <tr class="bg-gray-50">
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">部门</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">职称</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">人数</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="item in employeeCountByDeptAndTitle" :key="item.department_name + '-' + item.title_name">
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.department_name }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.title_name }}</td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ item.employee_count }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div class="bg-white p-6 rounded-lg shadow-md">
        <h3 class="text-lg font-medium mb-4">部门人数分布</h3>
        <div class="h-64">
          <canvas id="deptChart"></canvas>
        </div>
      </div>
    </div>

    <div class="bg-white p-6 rounded-lg shadow-md">
      <h3 class="text-lg font-medium mb-4">职称分布</h3>
      <div class="h-64">
        <canvas id="titleChart"></canvas>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import Chart from 'chart.js/auto'

const employeeCountByDeptAndTitle = ref([])
const TitleAtr = ref([])
const DeptAtr = ref([])

// 获取部门职称统计数据
const fetchReportData = async () => {
  try {
    // 获取部门职称统计

    const reportResponse = await axios.get('/api/analytics')
    employeeCountByDeptAndTitle.value = reportResponse.data.data
    // const  headerRes = await axios.get('/api/dash/header')
    //
    // TitleAtr.value = headerRes.data.data.titleResult
    // DeptAtr.value =  headerRes.data.data.deptResult
    ///
    const teacherResponse = await axios.get('/api/teacher/DashData')

    const teacher_data  = teacherResponse.data.data || {};
    let countMap = {};
    teacher_data.forEach(item => {
          const title = item.title;
          countMap[title] = (countMap[title] || 0) + item.teacher_count;
        });

    TitleAtr.value =  Object.keys(countMap).map(title => ({
          title: title,
          count: countMap[title]
        }));
    countMap = {};
    teacher_data.forEach(item => {
      const department = item.department;
      countMap[department] = (countMap[department] || 0) + item.teacher_count;
    });
    DeptAtr.value =  Object.keys(countMap).map(department => ({
      department: department,
      count: countMap[department]
    }));
    //
    initCharts()
  } catch (error) {
    initCharts()
    console.error('获取统计数据失败:', error)
    alert('获取统计数据失败，请稍后重试')
  }
}
// 生成动态颜色数组
function generateColors(count, opacity = 0.8) {
  const baseColors = [
    [22, 93, 255],   // 蓝色
    [54, 207, 201],  // 青色
    [82, 196, 26],   // 绿色
    [250, 173, 20],  // 黄色
    [255, 77, 79],   // 红色
    [140, 140, 140], // 灰色
    [115, 103, 240], // 紫色
    [234, 84, 85],   // 粉色
    [0, 201, 219],   // 青蓝色
    [253, 126, 20],  // 橙色
    [105, 108, 255], // 靛蓝色
    [64, 184, 131]   // 蓝绿色
  ];

  const colors = [];
  for (let i = 0; i < count; i++) {
    const color = baseColors[i % baseColors.length];
    colors.push(`rgba(${color[0]}, ${color[1]}, ${color[2]}, ${opacity})`);
  }

  return colors;
}

// 处理职称数据（用于柱形图）
function processTitleData(rawData) {
  // 按职称汇总人数（不分部门）
  const titleCounts = {};

  rawData.forEach(item => {
    const title = item.title || '未评级';
    titleCounts[title] = (titleCounts[title] || 0) + item.count;
  });
  console.log("titleCounts");
  console.log(titleCounts);
  // 转换为数组并按人数降序排序
  return Object.entries(titleCounts)
      .sort((a, b) => b[1] - a[1])
      .map(item => ({
        title: item[0],
        count: item[1]
      }));
}

// 处理部门数据（用于环形图）
function processDeptData(rawData) {
  // 按部门汇总人数（不分职称）
  const deptCounts = {};

  rawData.forEach(item => {
    const dept = item.department || '未分配部门';
    deptCounts[dept] = (deptCounts[dept] || 0) + item.count;
  });

  // 转换为数组并按人数排序
  return Object.entries(deptCounts)
      .sort((a, b) => b[1] - a[1])
      .map(item => ({
        name: item[0],
        count: item[1]
      }));
}

// 渲染职称分布柱形图
function renderTitleChart(titleData) {
  const titleCtx = document.getElementById('titleChart').getContext('2d');

  // 提取职称标签和计数
  const labels = titleData.map(item => item.title);
  const counts = titleData.map(item => item.count);

  // 生成动态颜色
  const backgroundColors = generateColors(labels.length, 0.8);
  const borderColors = generateColors(labels.length, 1);

  new Chart(titleCtx, {
    type: 'bar',
    data: {
      labels: labels,
      datasets: [{
        label: '人数',
        data: counts,
        backgroundColor: backgroundColors,
        borderColor: borderColors,
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      scales: {
        y: {
          beginAtZero: true,
          ticks: {
            precision: 0 // 只显示整数
          }
        }
      },
      plugins: {
        tooltip: {
          callbacks: {
            label: function(context) {
              return `${context.dataset.label}: ${context.raw}`;
            }
          }
        },
        legend: {
          display: false // 柱形图通常不需要图例
        }
      }
    }
  });
}

// 渲染部门人数环形图
function renderDeptChart(data) {
  const deptCtx = document.getElementById('deptChart').getContext('2d');

  // 如果部门超过10个，合并较小的部门为"其他"
  let displayData = data;
  if (data.length > 10) {
    const topData = data.slice(0, 9);
    const otherCount = data.slice(9).reduce((sum, item) => sum + item.count, 0);
    displayData = [...topData, { name: '其他', count: otherCount }];
  }

  const labels = displayData.map(item => item.name);
  const counts = displayData.map(item => item.count);

  // 生成动态颜色
  const backgroundColors = generateColors(labels.length, 0.8);
  const borderColors = backgroundColors.map(color => color.replace('0.8', '1'));

  new Chart(deptCtx, {
    type: 'doughnut',
    data: {
      labels: labels,
      datasets: [{
        data: counts,
        backgroundColor: backgroundColors,
        borderColor: borderColors,
        borderWidth: 1
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          position: 'bottom',
          labels: {
            boxWidth: 12,
            font: {
              size: 11
            }
          }
        },
        tooltip: {
          callbacks: {
            label: function(context) {
              const label = context.label || '';
              const value = context.raw || 0;
              const total = context.chart.getDatasetMeta(0).total;
              const percentage = Math.round((value / total) * 100);
              return `${label}: ${value}人 (${percentage}%)`;
            }
          }
        }
      }
    }
  });
}


const initCharts = () => {
  renderTitleChart(processTitleData(TitleAtr.value));
  renderDeptChart(processDeptData(DeptAtr.value));
};

onMounted(() => {
  fetchReportData()
})
</script>